package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"novel-mng/cache"
	"novel-mng/models"
	"strconv"
	"time"
)

func CarAdd(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_num := c.PostForm("car_num")
	data := models.Car{
		CarCode: car_code,
		CarName: car_name,
		CarNum:  car_num,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "车辆添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	OrderNo := c.PostForm("order_no")
	From_Add := c.PostForm("from_add")
	ToAdd := c.PostForm("to_add")
	Cid, _ := strconv.Atoi(c.PostForm("cid"))
	data := models.Order{
		OrderNo: OrderNo,
		FromAdd: From_Add,
		ToAdd:   ToAdd,
		Cid:     Cid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "订单添加成功",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var orderList []models.OrderList
	/*SELECT
	  orders.order_no AS OrderNo,
	  orders.from_add AS FromAdd,
	  orders.to_add as ToAdd,
	  cars.car_code AS CarCode,
	  cars.car_name AS CarName,
	  cars.car_num AS CarNum
	FROM
	  orders
	  LEFT JOIN cars ON cars.id=orders.cid*/
	redis_key := "data_list_page_" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cachejson == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN cars ON cars.id=orders.cid").
			Select(
				"orders.order_no AS OrderNo",
				"orders.from_add AS FromAdd",
				"orders.to_add as ToAdd",
				"cars.car_code AS CarCode",
				"cars.car_name AS CarName",
				"cars.car_num AS CarNum",
			).
			Offset(offset).Limit(size).Debug().Find(&orderList)
		jsondata, _ := json.Marshal(orderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &orderList)
	}
	var count int64
	models.DB.Model(&models.Order{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"count": count,
		"data":  orderList,
	})
	return
}
func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	var order models.Order
	redis_key := "data_detail_" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&order)
		json, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, json, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "订单添加成功",
		"data": order,
	})
	return
}
